<template>
  <form>
    <table>
      <tbody>
      <tr>
        <td>
          标题：
        </td>
        <td>
          <input type="text" v-model="formData.bookName" placeholder="请输入标题">
        </td>
      </tr>
      <tr>
        <td>
          作者:
        </td>
        <td>
          <input type="text" v-model="formData.bookAuthor" placeholder="请输入作者">
        </td>
      </tr>
      </tbody>
    </table>
    <input type="button" value="保存" @click="btnSave">
    <input type="button" value="取消" @click="btnCancel">
  </form>
</template>

<script setup>
import { addBook, editBook, getById } from '@/api/bookApi';
import { onMounted, reactive, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';



let router = useRouter();
let formData = reactive({
  bookName:'',
  bookAuthor:'',
})
let route = useRoute()

async function btnSave() {
  let id = route.params.id || 0
  let res;
  if(id>0){
    res = await editBook(id,formData)
  }else{
    res = await addBook(formData)
  }
  if(res.code = 1000){
    router.push('/books')
  }
}

function btnCancel(){
  router.push('/books')
}
onMounted(async () => {
  let id = route.params.id || 0;
  if(id>0){
    let res = await getById(id)
    formData.bookName = res.data.bookName
    formData.bookAuthor = res.data.bookAuthor

  }
})
</script>